package zhou.chs.p4_6;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    Button btStart;     //开始按钮
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btStart = (Button)findViewById(R.id.idbt);
        int i = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]);
        if (i != PackageManager.PERMISSION_GRANTED) {   //Android6.0需动态申请定位许可权限
            ActivityCompat.requestPermissions(this, permissions, 0);
        }
        if(isNetworkAvailable(this)){
            btStart.setEnabled(true);   //检测到可用网络，可以开始远程定位
        }else {
            Toast msg = Toast.makeText(this,"请连接网络后重启程序",Toast.LENGTH_LONG);
            msg.show();
        }
    }
    //开始按钮
    public void start(View view) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);   //运行服务程序
        moveTaskToBack(true);  //隐藏程序界面
    }
    //程序退出前的操作
    public void onDestroy() {
        super.onDestroy();
        Intent intentFour = new Intent(this, MyService.class);
        stopService(intentFour);        //停止服务程序
    }
    // 检查网络是否可用
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo minfo = manager.getActiveNetworkInfo();
        if (minfo == null || !minfo.isAvailable()) {
            return false;
        }
        return true;
    }
}
